www.gusucode.com > 关于海航matlab和lingo的训练题 > 人脸检测/face detection/detect.m

    % Given the original color image and the segmented image, displays a new image
% with rectangles indicating the face regions found.

function [imsource] = detect(imagecolor, imagesegmented)

clear

% Coordinates of possible faces are empty.
FaceCoord = [];

% ******** Read the template face image *********
frontalmodel = imread('frontal.tif');

% ********* Read the Source Images ************

% Read the source image in grayscale
imsource = imread(imagecolor);

% Get the skin color segmented image (black and white)
skincolor = imread(imagesegmented);
BW = im2bw(skincolor);


% **********************************

% Change the original image to gray scale.
imsourcegray = rgb2gray(imsource);
imshow(imsourcegray);

% Get the number of regions in the color skin segmented image

[L,numobj] = bwlabel(BW,8);

map = [0 0 0; jet(numobj)];
figure;
imshow(L+1, map,'notruesize');


 % Iterate through the number of objects (or regions) found in the
 % image.
 
for i=1:numobj,
     
   % Compute the coordinates for this region.
   [x,y] = find(bwlabel(BW) == i);
  
   % Get an image that only has this region, the rest is black
   bwsegment = bwselect(BW,y,x,8);
  
   % Compute the number of segments inside this region
   [L,numobjs] = bwlabel(bwsegment,4);
    
   % Get the number of holes.
   numfeatures = bweuler(bwsegment,4);
   numholes = 1 - numfeatures;
   
   % For now, a possible face needs to have more than one hole.
   % otherwise, it is discarded.
   
   if (numholes >= 1)
      
      % Get the rectangle coordinates if it is a region tha indicatesa
      % a face. 
      [RectCoord,imsourcegray] = processregion(imsourcegray,bwsegment,numholes,frontalmodel);
     
      % if the region is a facem add to a vector of face coordinates
      if (RectCoord ~= -1)
         FaceCoord = [FaceCoord; RectCoord];
      end;
   end;

end % for  


% ********************************************
%                 Final Output
% ********************************************

 % Display the original image with the region that is a face 
 figure;
 imshow(imsource);
 % display the rectangle(s) if we found face(s) in the image
 [numfaces x] = size(FaceCoord);
 for i=1:numfaces,
   hd = rectangle('Position',FaceCoord(i,:));
   set(hd, 'edgecolor', 'w');
 end;